#!/usr/bin/python

# 2/17/11, Lee Magnusson
# I've got data from the s08dz as received through mcu2k, I had some program befor that parsed the json files, but can't find it now. Here goes again

from optparse import OptionParser
import json
import re

parser = OptionParser('usage: %prog [options] filename')
parser.add_option("-p", "--pgn", dest="pgn_mask", 
                  help="only print out messages from PGN", 
                  metavar="PGN", type='int')
parser.add_option("-f", "--field_value", dest="field_mask",
                  help="only print out messages that match field as specified" +
                  "pipe separate the field from the value",
                  metavar="FIELD_VALUE", type='string')
parser.add_option("-o", "--output_field", dest="output_fields",
                  help="only print out the specified fields, quote pipe separate",
                  metavar="OUTPUT_FIELDS", type='string')
parser.add_option("-c", "--csv", dest="output_csv", action='store_true',
					help = "print out as csv", default=False)
(opts,args) = parser.parse_args()
if len(args) != 1:
    parser.error("specify 1 filename")
filename = args[0]

p = re.compile(r'^s08dz published: (?P<d>\{.*\})$')
p = re.compile(r'^(?P<d>\{.*\})$')
with open(filename) as f:
    for l in f:
        m = p.match(l)
        if m:
            dj = json.loads(m.group('d'))
            if opts.pgn_mask and dj['pgn'] != opts.pgn_mask:
                continue         
            if opts.field_mask:
                fcheck = opts.field_mask.split('|')
                if str(dj['fields'][fcheck[0]][0]) != fcheck[1]:
                    continue

            #print(m.group('d'))
            if opts.output_fields:
                field_list = [ dj['fields'].get(ofield,[None])[0]
                  for ofield in opts.output_fields.split('|')]
                if any(field_list):
                    print(','.join([str(f) if f else 'Nan' for f in field_list]))
            else:
                print(dj)

